<template>
  <div class="type-tab" :style="{'--bgColor': bgColor}">
    <div
      class="tab-item"
      :class="{ active: selectTabIndex == i }"
      :style="{'--color': activeColor}"
      v-for="(tab, i) in data"
      :key="i"
      @click="handleTabSelect(i)"
    >
      {{ tab.label }}
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
const props = defineProps({
  modelValue: {
    type: Number,
    default: 0
  },
  data: {
    type: Array,
    default: () => []
    // {label, value}
  },
  activeColor: {
    type: String,
    default: '#333'
  },
  bgColor: {
    type: String,
    default: '#eee'
  }
})

const emit = defineEmits(['update:modelValue', 'on-change']);

// Tab 下标
const selectTabIndex = ref(0);

onMounted(() => {
  // 初始化：根据value设置下标
  const index = props.modelValue ? props.data.findIndex(item => item.value == props.modelValue) : 0;
  selectTabIndex.value = index;
})
// Tab切换 
const handleTabSelect = index => {
  if (index == selectTabIndex.value) return;
  selectTabIndex.value = index;
  const value = props.data[index].value;
  emit('update:modelValue', value);
  emit('on-change', value);
}

</script>
<style lang="scss" scoped>
.type-tab {
  display: flex;
  align-items: center;
  background-color: var(--bgColor);
  border-radius: 8px;
  padding: 4px;
  margin-bottom: 20px;
  .tab-item {
    width: 50%;
    color: #999;
    text-align: center;
    border-radius: 8px;
    padding: 2px 0;
    transition: all .2s ease-in;
    cursor: pointer;
    font-weight: 600;
    user-select: none;

    &.active {
      color: var(--color);
      background-color: #fff;
    }
  }
}
</style>